import hashlib
from app.schemas.callback import CallbackResponse
from app.core.config import settings

def verify_signature(signature: str, uid: str, id: str) -> bool:
    """
    验证签名
    """
    expected_signature = hashlib.md5(f"{uid}{id}{settings.PPT_API_KEY}".encode()).hexdigest()
    return signature == expected_signature

async def handle_ppt_callback(signature: str, body: dict) -> CallbackResponse:
    """
    处理 PPT 生成回调
    """
    try:
        # 获取数据
        data = body.get("data", {})
        uid = data.get("uid")
        ppt_id = data.get("pptId")
        
        # 验证签名
        if not verify_signature(signature, uid, ppt_id):
            return CallbackResponse(ok=False, msg="Invalid signature")
            
        # 如果是测试请求，直接返回成功
        if ppt_id == "test":
            return CallbackResponse(ok=True, msg="Test callback successful")
            
        # TODO: 处理实际的 PPT 生成回调
        # 这里可以添加您的业务逻辑，比如：
        # 1. 更新数据库中的 PPT 状态
        # 2. 发送通知给用户
        # 3. 触发其他业务流程
        
        return CallbackResponse(ok=True, msg="Callback processed successfully")
    except Exception as e:
        return CallbackResponse(ok=False, msg=str(e))

async def handle_template_callback(signature: str, body: dict) -> CallbackResponse:
    """
    处理模板上传回调
    """
    try:
        # 获取数据
        data = body.get("data", {})
        uid = data.get("uid")
        template_id = data.get("templateId")
        
        # 验证签名
        if not verify_signature(signature, uid, template_id):
            return CallbackResponse(ok=False, msg="Invalid signature")
            
        # 如果是测试请求，直接返回成功
        if template_id == "test":
            return CallbackResponse(ok=True, msg="Test callback successful")
            
        # TODO: 处理实际的模板上传回调
        # 这里可以添加业务逻辑，比如：
        # 1. 更新数据库中的模板状态
        # 2. 发送通知给用户
        # 3. 触发其他业务流程
        
        return CallbackResponse(ok=True, msg="Callback processed successfully")
    except Exception as e:
        return CallbackResponse(ok=False, msg=str(e)) 